package com.nts.pmchelperdemo3.controller;

import com.nts.pmchelperdemo3.dto.OrderDTO;
import com.nts.pmchelperdemo3.result.Result;
import com.nts.pmchelperdemo3.service.OrderService;
import com.nts.pmchelperdemo3.util.ResultUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 订单管理控制器（处理订单创建、查询、状态更新等）
 */
@RestController
@RequestMapping("/api/orders")
@Slf4j
@Api(tags = "订单管理接口")
public class OrderController {

    @Autowired
    private OrderService orderService;

    /**
     * 创建订单（区分普通刀/定制刀）
     */
    @PostMapping
    @ApiOperation("创建新订单（普通刀自动匹配时间，定制刀需输入时间）")
    public Result<OrderDTO> createOrder(@RequestBody OrderDTO orderDTO) {
        OrderDTO createdOrder = orderService.createOrder(orderDTO);

        return ResultUtil.success(createdOrder, "订单创建成功");
    }

    /**
     * 查询所有订单
     */
    @GetMapping
    @ApiOperation("查询所有订单列表")
    public Result<List<OrderDTO>> getAllOrders(
            @RequestParam(required = false) Integer status,  // 可选：按状态筛选
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {
        List<OrderDTO> orders = orderService.queryOrders(status, page, size);
        return ResultUtil.success(orders, "订单查询成功");
    }

    /**
     * 查询单个订单详情
     */
    @GetMapping("/{id}")
    @ApiOperation("查询订单详情")
    public Result<OrderDTO> getOrderById(@PathVariable Long id) {
        OrderDTO orderDTO = orderService.getOrderById(id);
        return ResultUtil.success(orderDTO, "订单详情查询成功");
    }

    /**
     * 更新订单状态（如：磨刀完成→涂层中）
     */
    @PutMapping("/{id}/status")
    @ApiOperation("更新订单状态（仅支持特定状态流转）")
    public Result<OrderDTO> updateOrderStatus(
            @PathVariable Long id,
            @RequestParam Integer newStatus) {
        OrderDTO updatedOrder = orderService.updateOrderStatus(id, newStatus);
        return ResultUtil.success(updatedOrder, "订单状态更新成功");
    }

    /**
     * 删除订单（仅支持“接单中”状态的订单）
     */
    @DeleteMapping("/{id}")
    @ApiOperation("删除订单（仅接单中状态可删除）")
    public Result<Void> deleteOrder(@PathVariable Long id) {
        orderService.deleteOrder(id);
        return ResultUtil.success(null, "订单删除成功");
    }

    @GetMapping("/count")
    @ApiOperation("查询特定状态下的订单总数")
    public Result<Integer> getOrderCountByStatus(@RequestParam Integer status){
        int count  = orderService.countOrderByStatus(status);
        return ResultUtil.success(count,"订单数量查询成功");
    }

}
